import './libs/weapp-adapter'
import * as PIXI from './libs/pixi.min'
import * as filters from './libs/pixi-filters'

const {pixelRatio, windowWidth, windowHeight} = wx.getSystemInfoSync()

const app = new PIXI.Application({
    width: windowWidth * pixelRatio,
    height: windowHeight * pixelRatio,
    view: canvas
})

app.renderer.plugins.interaction.mapPositionToPoint = (point, x, y) => {
    point.x = x * pixelRatio
    point.y = y * pixelRatio
}

const
    bounds = new PIXI.Rectangle(-100, -100, app.view.width + 200, app.view.height + 200),
    bkg = PIXI.Sprite.fromImage('./textures/bkg.jpg'),
    fishes = [],
    waveFilter =  new filters.ShockwaveFilter({
        speed: 10,
        amplitude: 10
    }),
    overlay = new PIXI.extras.TilingSprite(
        PIXI.Texture.fromImage('./textures/overlay.png'),
        app.view.width,
        app.view.height
    )

waveFilter.enabled = false
app.stage.filters = [waveFilter]
app.stage.filterArea = app.screen

bkg.texture.on('update', () => {
    bkg.scale.set(Math.max(app.view.width / bkg.width, app.view.height / bkg.height))
})

app.stage.addChild(bkg)

/* add fish */
for (let i = 0; i < 20; i++) {
    const fish = PIXI.Sprite.fromImage(`./textures/fish.${i % 4 + 1}.png`)

    fish.direction = Math.random() * Math.PI * 2
    fish.speed = 2 + Math.random() * 2
    fish.turnSpeed = Math.random() - 0.8

    fish.anchor.set(.5)

    fish.position.set(
        Math.random() * app.view.width,
        Math.random() * app.view.height
    )

    fishes.push(fish)
    app.stage.addChild(fish)
}

app.stage.addChild(overlay)

bkg.interactive = true
bkg.on('pointerdown', ev => {
    waveFilter.enabled = true
    waveFilter.center = [ev.data.global.x, ev.data.global.y]
    waveFilter.time = 0
})

app.ticker.add(dt => {
    for (const fish of fishes) {

        fish.direction += fish.turnSpeed * 0.01;

        fish.x += Math.sin(fish.direction) * fish.speed;
        fish.y += Math.cos(fish.direction) * fish.speed;

        fish.rotation = -fish.direction - Math.PI/2;

        fish.x < bounds.x ? fish.x += bounds.width :
        fish.x > bounds.x + bounds.width ? fish.x -= bounds.width : null
        fish.y < bounds.y ? fish.y += bounds.height :
        fish.y > bounds.y + bounds.height ? fish.y -= bounds.height : null
    }


    overlay.tilePosition.x -= dt
    overlay.tilePosition.y -= dt

    overlay.tilePosition.x %= 512
    overlay.tilePosition.y %= 512

    if (waveFilter.enabled) {
        waveFilter.time += app.ticker.elapsedMS / 1000
        waveFilter.time > 3 ? waveFilter.enabled = false : null
    }
})